let express = require('express');
let router = express.Router();

let PictureService = require('../services/PictureService');

const UUID = require('node-uuid');
const OSS = require('ali-oss');

const MultipartMiddleware = require('connect-multiparty')();

const file_types = ['image','css','js','html'];
const suf_types = {
    image: /.(gif|jpg|jpeg|png|GIF|JPG|JPEG|PNG)$/,
    css: /.css$/,
    js: /.js$/,
    html: /.html$/
}
const validator = {
    id: '请检查id',
    address: '请先上传文件',
    label: '请输入图片名称（标签）'
}

function validResParam(keyArr, item, done){
    let valid = true;
    for (let k of keyArr) {
        if(!item[k]){
            var msg = validator[k];
            valid = false;
            break;
        }
    }
    if(!valid) done.status(400).send({code: 400, msg});
    return valid;
}

router.get('/', (req, res, next) => {
    res.send({
        code: 200,
        data: null,
        msg: '游客接口请求成功'
    })
});
// 上传文件
router.post('/file/upload', MultipartMiddleware, (req, res, next) => {
    let {body, files} = req;
    // 必填项目描述【标签】，筛选起来一目了然
    if(!body.label) {
        res.status(400).send({code: 400, msg: '请在上传组件添加参数[label:项目名称]'})
        return;
    }

    let file = files['miao'];
    if(!file) {
        res.status(400).send({code: 400, msg: '请在上传组件添加配置属性[name]'})
        return;
    }
    // 文件后缀
    let _suf_name = /\.[^\.]+$/.exec(file.name);
    if(file.name == 'blob') {
        _suf_name = '.png'
    } else {
        // 目前只提供图片上传
        if(!suf_types['image'].test(_suf_name)) {
            res.status(400).send({code: 400, msg: '文件格式不正确'})
            return;
        }
    }

    // 随机文件名
    let _f_name = UUID.v1();
    try {
        let Client = new OSS($config._aoc.conf);
        let uri = $config._aoc.path  + 'file/' + _f_name + _suf_name;

        Client.put(uri, file.path).then(result => {
            res.send({
                code: 200,
                data: $config._aoc.domain + result.name,
                msg: '上传成功'
            })
            PictureService.createPic({
                file_type: 'tourist_image',
                label: body.label,
                address: $config._aoc.domain + result.name,
                operator_id: -1
            });
        })
    } catch (e) {
        next(e);
    }
});
// 文件列表
router.get('/file/list', async ctx => {
    let data = await PictureService.getPicList(Object.assign(ctx.query, {file_type: 'tourist_image'}), ctx.next);
    ctx.res.send($utils._formmat_send_data({data}));
});

module.exports = router;
